package pub.wkq.common.exception;

import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.UnsupportedJwtException;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import pub.wkq.common.result.JSONResult;
import pub.wkq.common.result.ResponseStatusEnum;

import java.security.SignatureException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 通过切面捕获异常
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public JSONResult returnCustomException(CustomException e) {
        e.printStackTrace();
        return JSONResult.exception(e.getResponseStatusEnum());
    }

    /**
     * 处理 Springboot 校验框架的异常
     */
    @ExceptionHandler(org.springframework.validation.BindException.class)
    @ResponseBody
    public JSONResult returnBindException(org.springframework.validation.BindException e) {
        //获取所有异常信息，组装成 Map<String,String> ,key 是字段名，value 是错误信息
        Map<String, String> field2Message = e.getBindingResult().getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
        return JSONResult.errorMap(field2Message);
    }

    /**
     * 处理 除零异常
     */
      @ExceptionHandler(ArithmeticException.class)
        @ResponseBody
        public JSONResult returnArithmeticException(ArithmeticException e) {
            e.printStackTrace();
          return JSONResult.errorMsg(e.getMessage());
        }


    @ExceptionHandler({
            SignatureException.class,
            ExpiredJwtException.class,
            UnsupportedJwtException.class,
            MalformedJwtException.class,
            io.jsonwebtoken.security.SignatureException.class
    })
    @ResponseBody
    public JSONResult returnJWTException(SignatureException e) {
        e.printStackTrace();
        return JSONResult.exception(ResponseStatusEnum.JWT_SIGNATURE_ERROR);
    }

}
